import React, {ButtonHTMLAttributes, useState} from 'react';
import {NumberWrapper, Wrapper} from './NumberPadSection/Wrapper';
import {generateOutput} from './NumberPadSection/generateOuput';

type Props = {
  value: number;
  onOutputChange: (newValue: number) => void;
  onOk: () => void;
}

type NumberProps = {
  text: string;
  className?:string;
} & ButtonHTMLAttributes<HTMLElement>
const NumberButton: React.FC<NumberProps> = (props) => {
  const {className, ...otherProps} = props
  return (
    <NumberWrapper className={className}>
      <button {...otherProps}>{props.text}</button>
    </NumberWrapper>
  )
}

const NumberPadSection: React.FC<Props> = (props) => {
  const [output, _setOutput] = useState<string>(Math.abs(props.value).toString());
  const setOutput = (newState: string) => {
    if (newState.length >= 16) {return;}
    if (newState.length === 0) {newState = '0';}
    _setOutput(newState);
    props.onOutputChange(parseFloat(newState));
  };
  const onClickButtonWrapper = (e: React.MouseEvent) => {
    const text = (e.target as HTMLButtonElement).textContent;
    if (text === null) { return; }
    if (text === '确认') {
      props.onOk();
      _setOutput('0');
      return;
    }
    if ('0123456789.'.split('').concat(['删除', '清空']).indexOf(text) >= 0) {
      setOutput(generateOutput(text, output));
    }
  };

  return (
    <Wrapper>
      <div className="output">{output}</div>
      <div className="pad clearfix" onClick={onClickButtonWrapper}>
        <NumberButton text="1" />
        <NumberButton text="2" />
        <NumberButton text="3" />
        <NumberButton text="删除" />
        <NumberButton text="4" />
        <NumberButton text="5" />
        <NumberButton text="6" />
        <NumberButton text="清空" />
        <NumberButton text="7" />
        <NumberButton text="8" />
        <NumberButton text="9" />
        <NumberButton className="enter" disabled={output === '0'} text="确认" />
        <NumberButton className="zero" text="0" />
        <NumberButton text="." />
      </div>
    </Wrapper>
  );
};
export {NumberPadSection};